import { Injectable, enableProdMode } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';

import { NzMessageService } from 'ng-zorro-antd';
import { StorageService } from '../services/storage.service';

enableProdMode();

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private messageService: NzMessageService, private storage: StorageService, private router: Router) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        const JWT = this.storage.get('token');
        const jwtReq = (JWT == null) ? req : req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + JWT) });
        // return next.handle(jwtReq);
        return next.handle(jwtReq).do(event => {
            // const elapsed = Date.now() - started;
            // console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
            if (event instanceof HttpResponse) {
                if (event.ok) {
                    // this.messageService.success('请求成功！');
                    return event;
                }
            }
        }).catch((err: any) => {
            if (err.error instanceof Error) {
                this.messageService.error('网络异常', err.error.message);
                // A client-side or network error occurred. Handle it accordingly.
                console.log('An error occurred:', err.error.message);
            } else {
                switch (err.status) {
                    case 400:
                        return Observable.throw(err.error);
                    case 401:
                        this.messageService.error('未登录/登录超时');
                        this.storage.remove('token');
                        this.router.navigate(['/single/signin']);
                        break;
                    case 403:
                        this.messageService.error('无权访问');
                        break;
                    case 404:
                        this.messageService.error('错误的请求地址');
                        break;
                    case 500:
                        this.messageService.error('服务器异常');
                        break;
                    case 504:
                        this.messageService.error('请求超时');
                        break;
                    default:
                        this.messageService.error('故障', err.error);
                        break;
                }
                console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
            }
            return Observable.throw(err.error);
        });
        // .map(
        //     (res: any) => {
        //         if (res instanceof HttpResponse) {
        //             if (res.ok) {
        //                 this.notify.success('OK', '请求成功！');
        //                 return res;
        //             }
        //         }
        //     },
        //     (err: any) => {
        //         if (err.error instanceof Error) {
        //             this.notify.error('网络异常', err.error.message);
        //             // A client-side or network error occurred. Handle it accordingly.
        //             console.log('An error occurred:', err.error.message);
        //         } else {
        //             switch (err.status) {
        //                 case 401:
        //                     this.notify.error('401', '未登录系统');
        //                     this.storage.remove('token');
        //                     this.router.navigate(['/login']);
        //                     break;
        //                 case 403:
        //                     this.notify.error('403', '登录超时');
        //                     this.storage.remove('token');
        //                     this.router.navigate(['/login']);
        //                     break;
        //                 case 404:
        //                     this.notify.error('404', '错误的请求地址');
        //                     break;
        //                 case 500:
        //                     this.notify.error('500', '服务器异常');
        //                     break;
        //                 default:
        //                     this.notify.error('故障', err.error.message);
        //                     break;
        //             }
        //             // The backend returned an unsuccessful response code.
        //             // The response body may contain clues as to what went wrong,
        //             console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        //         }
        //         return Observable.throw(err);
        //     });


    }
}
